package middleware

import (
	"fmt"
	"net/http"
	"time"

	"gitee.com/xixigroup/sweet-tools/base/logger"
	"github.com/gin-gonic/gin"
)

func Logger() gin.HandlerFunc {
	return func(c *gin.Context) {
		start := time.Now()

		c.Next()

		url := c.Request.URL.String()
		method := c.Request.Method
		statusCode := c.Writer.Status()
		latency := time.Now().Sub(start)
		client := c.ClientIP()
		//size := c.Writer.Size()

		msg := fmt.Sprintf("%d %s %s (%s) %v", statusCode, method, url, client, latency)

		if statusCode < http.StatusInternalServerError && statusCode >= http.StatusBadRequest {
			logger.Warn(msg)
		} else if statusCode >= http.StatusInternalServerError {
			logger.Error(msg)
		} else {
			logger.Info(msg)
		}
	}
}
